package top.codedance.iotp.client.net.listenner;

import cd.io.netty.channel.ChannelFuture;
import cd.io.netty.channel.ChannelFutureListener;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.ClientApplication;
import top.codedance.iotp.client.net.Client;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.common.util.OSinfo;
import top.codedance.iotp.common.util.SystemUtil;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectionListener implements ChannelFutureListener {

    private static Logger logger = ClientApplication.getLogger(ConnectionListener.class);
    private Client client;

    public ConnectionListener(Client client){
        this.client = client;
    }

    public void operationComplete(final ChannelFuture future) {
        if (future.isSuccess() && future.channel().isActive()) {
            logger.debug("Connect the server success");
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!future.channel().isActive()){
                        timer.cancel();
                    }
                    try {
                        CommonEntity commonEntity = new CommonEntity();
                        commonEntity.setCommand(Command.REPORT_LOAD);
                        JSONObject jo = new JSONObject();
                        jo.put("deviceId", ClientApplication.DEVICE_ID);
                        jo.put("load", SystemUtil.getSystemUsage());
                        jo.put("os", OSinfo.getOSname());
                        commonEntity.setBody(jo.toJSONString().getBytes(StandardCharsets.UTF_8));
                        future.channel().writeAndFlush(commonEntity);
                        logger.debug("Up load: " + SystemUtil.getSystemUsage().toJSONString());
                    }catch (Exception e){
                        logger.debug(e.getMessage());
                    }
                }
            }, 1000l * 20, 1000l * 20);
        }else{
            future.cancel(true);
        }
    }
}
